import React, {useEffect, useState} from 'react';
import {Form} from 'antd';
import {ProForm} from '@ant-design/pro-components';
import PageModal from '@components/page_modal';
import {request} from "@utils/request.js";
import {getForm} from "@pages/crud/index.jsx";

const getParamInfo = (key, label, valid) => {
    let arr = key.split('-')
    let prop = arr[0]
    let type = arr[1] || 'other'
    if (prop === 'id') return
    valid = valid[arr[0]] || {}
    let required = eval(valid[arr[0]]?.required || false);
    return {type, prop, label, valid, required}
}

export default (props) => {
    const {operation, onCancel, detail, onOk} = props;
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [dom, setDom] = useState([]);
    const [width, setWidth] = useState(500);

    const save = async (params) => {
        setLoading(true);
        if (detail.id) params.id = detail.id
        for (const key in params) params[key] = params[key] === undefined ? null : params[key]
        await request(operation.url, params)
        onOk();
        setLoading(false);
    };

    const getFormFieldDom = async ({key, label, valid}) => {
        let info = getParamInfo(key, label, valid)
        if (info === undefined) return null
        if (info.valid?.['formWidth'] && info.valid?.['formWidth'] > width) setWidth(info.valid['formWidth'])
        return await getForm(info)
    }

    useEffect(() => {
        form.setFieldsValue(detail);
    }, [detail]);

    useEffect(() => {
        let keys = Object.keys(operation.req)
        Promise.all(keys.map(async (e) => getFormFieldDom({
            key: e,
            label: operation.req[e],
            valid: operation.valid
        }))).then(res => {
            setDom(res.filter(e => e))
        })
        return () => console.log('销毁')
    }, []);
    return (
        <>
            <PageModal
                title={detail.id ? '编辑' : '新建'}
                open={true}
                onCancel={onCancel}
                confirmLoading={loading}
                width={width}
                onOk={() => {
                    form.validateFields()
                        .then(save)
                        .catch(() => {
                        });
                }}>
                <ProForm
                    form={form}
                    layout="horizontal"
                    labelCol={{span: 4}}
                    wrapperCol={{span: 20}}
                    submitter={{
                        render: () => {
                            return [];
                        },
                    }}>
                    {dom}
                </ProForm>
            </PageModal>
        </>
    );
}
